/**
 * ______________________________________________________________________________
 *
 * File: StartMigration.java
 *______________________________________________________________________________
 *
 * CreatedBy: Verinon
 * CreationDate: Sep 10, 2012   1:31:14 PM   2012
 * Description: Write your class description here like from where it is calling and
 * what functions are doing
 *______________________________________________________________________________
 *
 * Copyright: (c) Vietinbank, all rights reserved 
 *______________________________________________________________________________
 *
 */
package com.vb.ecm.migration.icdoc;

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.SwingWorker;

import org.apache.log4j.Logger;

import com.documentum.fc.client.IDfSession;
import com.documentum.fc.common.DfException;

/**
 * @Last Midify Author Verinon
 * @Last Midification Date Sep 10, 2012
 * @Last Midification Time 1:31:14 PM
 * @Last Midification Year 2012
 * @What to do next TODO
 */
public class StartMigration extends JFrame implements ActionListener {

	private static ResourceBundle RSB = ResourceBundle.getBundle("com.vb.ecm.migration.icdoc.migrationtool");
	private static final Logger LOGGER = Logger.getLogger(StartMigration.class);
	ExportToDocumentum etd = new ExportToDocumentum();
	AccessDatabase accessDatabase = new AccessDatabase();
	
	private static String REPOSITORYNAME = RSB.getString("REPOSITORY_NAME");
	private static String USERNAME = RSB.getString("USERNAME");
	private static String PASSWORD = RSB.getString("PASSWORD");	
	private static String ICDOCFOLDERSTABLE = RSB.getString("ICDOCFOLDERSTABLE");	
	public static String CURRENTDIRECTORY = null;
	

	private IDfSession session;

	JLabel line1Label, line2Label, line3Label, logoLabel, connectionDetailsLablel, dataBaseNameLabel, dataBaseUserIdLabel, dataBasePasswordLablel, connectionStatusLable,
			migrationDetailsLablel, folderPathLabel, branchCodeLabel, copyRightLabel;
	JTextField dataBaseNameTextField, dataBaseUserIdTextField, connectionStatusTextField, branchNameTextField, folderPathTextField;
	JButton connectButton, getBranchButton, browseButton, startButton, stopButton, rerunDocButton, rerunFolButton, viewReportButton;
	JComboBox branchCodeDropDown;
	JProgressBar progressBar;
	JPasswordField dataBasePasswordTextField;

	Connection sqlconnection, accessConnection = null;
	Statement statement1, statement2, statement3, accessStatement = null;
	ResultSet folderResultset = null;
	
	Thread extractExportThread, extractExportProgressBarThread, extractExportFailedDocsThread, extractExportFailedFolderThread;

	
	int noOfIngestedFolders = 0;
	int MAX = 0;
	long WAIT = 1000;
	private int current;

	private SimulatedActivity activity;

	/**
	 * 
	 */
	public StartMigration() {
		// TODO Auto-generated constructor stub
		LOGGER.debug("StartMigration  :: StartMigration :: Enter Constructor");
		// Container Declaration
		Container container = getContentPane();
		container.setLayout(null);
		setResizable(false);
		container.setBackground(new Color(204, 204, 255));

		/**
		 * Migration Tool GUI All Labels are defined here
		 * 
		 */
		logoLabel = new JLabel();
		logoLabel.setForeground(new Color(001, 001, 001));
		logoLabel.setFont(new Font("Dialog", Font.BOLD, 13));
		logoLabel.setText("icDoc Migration Tool V1.2");
		logoLabel.setBounds(610, 0, 400, 50);
		container.add(logoLabel);

		line1Label = new JLabel();
		line1Label.setForeground(new Color(180, 180, 255));
		line1Label.setFont(new Font("Dialog", Font.BOLD, 10));
		line1Label.setText("______________________________________________________________________________________________________________________________________________");
		line1Label.setBounds(000, 30, 900, 30);
		container.add(line1Label);

		line2Label = new JLabel();
		line2Label.setForeground(new Color(180, 180, 255));
		line2Label.setFont(new Font("Dialog", Font.BOLD, 10));
		line2Label.setText("______________________________________________________________________________________________________________________________________________");
		line2Label.setBounds(000, 220, 900, 30);
		container.add(line2Label);

		line3Label = new JLabel();
		line3Label.setForeground(new Color(180, 180, 255));
		line3Label.setFont(new Font("Dialog", Font.BOLD, 10));
		line3Label.setText("______________________________________________________________________________________________________________________________________________");
		line3Label.setBounds(000, 480, 900, 30);
		container.add(line3Label);

		connectionDetailsLablel = new JLabel();
		connectionDetailsLablel.setText("Connection Details:");
		connectionDetailsLablel.setBounds(020, 50, 300, 50);
		connectionDetailsLablel.setForeground(new Color(001, 001, 001));
		container.add(connectionDetailsLablel);

		dataBaseNameLabel = new JLabel();
		dataBaseNameLabel.setText("Source Database Name");
		dataBaseNameLabel.setBounds(140, 100, 500, 50);
		dataBaseNameLabel.setForeground(new Color(001, 001, 001));
		container.add(dataBaseNameLabel);

		dataBaseUserIdLabel = new JLabel();
		dataBaseUserIdLabel.setText("Database User ID");
		dataBaseUserIdLabel.setBounds(140, 130, 500, 50);
		dataBaseUserIdLabel.setForeground(new Color(001, 001, 001));
		container.add(dataBaseUserIdLabel);

		dataBasePasswordLablel = new JLabel();
		dataBasePasswordLablel.setText("Database User Password");
		dataBasePasswordLablel.setBounds(140, 160, 500, 50);
		dataBasePasswordLablel.setForeground(new Color(001, 001, 001));
		container.add(dataBasePasswordLablel);

		connectionStatusLable = new JLabel();
		connectionStatusLable.setText("Connection Status");
		connectionStatusLable.setBounds(140, 190, 500, 50);
		connectionStatusLable.setForeground(new Color(001, 001, 001));
		container.add(connectionStatusLable);

		migrationDetailsLablel = new JLabel();
		migrationDetailsLablel.setText("Migration Details:");
		migrationDetailsLablel.setBounds(020, 230, 300, 50);
		migrationDetailsLablel.setForeground(new Color(001, 001, 001));
		container.add(migrationDetailsLablel);

		branchCodeLabel = new JLabel();
		branchCodeLabel.setText("Branch Code");
		branchCodeLabel.setBounds(140, 280, 500, 50);
		branchCodeLabel.setForeground(new Color(001, 001, 001));
		container.add(branchCodeLabel);

		folderPathLabel = new JLabel();
		folderPathLabel.setText("Source Folder Path");
		folderPathLabel.setBounds(140, 310, 500, 50);
		folderPathLabel.setForeground(new Color(001, 001, 001));
		container.add(folderPathLabel);

		Font font = new Font("Arial", Font.ITALIC, 10);
		copyRightLabel = new JLabel();
		copyRightLabel.setFont(font);
		copyRightLabel.setText("This tool is used to migrate content and metadata from icDoc to ECM repository, before start migration please refert to Migration tool user guide");
		copyRightLabel.setBounds(000, 510, 900, 30);
		copyRightLabel.setForeground(new Color(001, 001, 001));
		container.add(copyRightLabel);

		Font font2 = new Font("Arial", Font.ITALIC, 10);
		copyRightLabel = new JLabel();
		copyRightLabel.setFont(font2);
		copyRightLabel.setText("Copyright: (c) Vietinbank ECM 2012, all rights reserved");
		copyRightLabel.setBounds(530, 540, 900, 30);
		copyRightLabel.setForeground(new Color(001, 001, 001));
		container.add(copyRightLabel);

		/**
		 * Migration Tool GUI All Text fields are defined here
		 * 
		 */
		//dataBaseNameTextField = new JTextField("HQ-ECMDTS-DEV.hq.icbv.com");
		dataBaseNameTextField = new JTextField();
		dataBaseNameTextField.setBounds(300, 114, 140, 20);
		container.add(dataBaseNameTextField);

		//dataBaseUserIdTextField = new JTextField("sa");
		dataBaseUserIdTextField = new JTextField();
		dataBaseUserIdTextField.setBounds(300, 145, 140, 20);
		container.add(dataBaseUserIdTextField);

		//dataBasePasswordTextField = new JPasswordField("Abc@123456");
		dataBasePasswordTextField = new JPasswordField();
		dataBasePasswordTextField.setBounds(300, 178, 140, 20);
		container.add(dataBasePasswordTextField);

		connectionStatusTextField = new JTextField();
		connectionStatusTextField.setEditable(false);
		connectionStatusTextField.setBounds(480, 210, 140, 20);
		container.add(connectionStatusTextField);
		
		branchNameTextField = new JTextField();
		branchNameTextField.setEditable(false);
		branchNameTextField.setBounds(440, 290, 140, 20);
		container.add(branchNameTextField);

		//folderPathTextField = new JTextField("C:\\01-VERINON\\01-Projects\\10 Vietin Bank\\60 Docs From VietinBank\\icDoc\\iCdoc Files\\iCdoc Files\\91f3a2c0e4424c87689525da44c4db11");
		folderPathTextField = new JTextField();
		folderPathTextField.setBounds(300, 325, 280, 20);
		folderPathTextField.setEditable(false);
		container.add(folderPathTextField);
// "Branch 001", "Branch 002", "Branch 003", "Branch 004", "Branch 005", "Branch 006", "Branch 007", "Branch 008", "Branch 009", "Branch 010"
		//String course[] = {};
		branchCodeDropDown = new JComboBox();
		branchCodeDropDown.setBounds(300, 290, 120, 22);
		container.add(branchCodeDropDown);

		/**
		 * Migration Tool GUI progress bar
		 * 
		 */
		progressBar = new JProgressBar();
		// progressBar.setString("Please wait...");
		progressBar.setBounds(140, 450, 600, 30);
		progressBar.setStringPainted(true);
		container.add(progressBar);

		/**
		 * Migration Tool GUI All Buttons are defined here
		 * 
		 */
		connectButton = new JButton("Connect");
		connectButton.setText("Connect");
		connectButton.setBounds(300, 210, 140, 20);
		container.add(connectButton);
		connectButton.addActionListener(this);
		
		getBranchButton = new JButton("Get Branch Details");
		getBranchButton.setText("Get Branch Details");
		getBranchButton.setBounds(600, 290, 140, 20);
		container.add(getBranchButton);
		getBranchButton.addActionListener(this);


		browseButton = new JButton("Browse");
		browseButton.setText("Browse");
		browseButton.setBounds(600, 325, 140, 20);
		container.add(browseButton);
		browseButton.addActionListener(this);

		startButton = new JButton("Start");
		startButton.setText("Start");
		startButton.setBounds(140, 380, 100, 20);
		container.add(startButton);
		startButton.addActionListener(this);

		stopButton = new JButton("Stop");
		stopButton.setText("Stop");
		stopButton.setBounds(260, 380, 100, 20);
		container.add(stopButton);
		stopButton.addActionListener(this);

		rerunDocButton = new JButton("RerunDocs");
		rerunDocButton.setText("RerunDocs");
		rerunDocButton.setBounds(380, 380, 100, 20);
		container.add(rerunDocButton);
		rerunDocButton.addActionListener(this);
		
		rerunFolButton = new JButton("RerunFolder");
		rerunFolButton.setText("RerunFolder");
		rerunFolButton.setBounds(500, 380, 120, 20);
		container.add(rerunFolButton);
		rerunFolButton.addActionListener(this);

		viewReportButton = new JButton("ViewReport");
		viewReportButton.setText("ViewReport");
		viewReportButton.setBounds(640, 380, 100, 20);
		container.add(viewReportButton);
		viewReportButton.addActionListener(this);

		/**
		 * Migration Tool GUI Image defined here
		 * 
		 */
		//ImageIcon ic1 = new ImageIcon("C:\\Users\\Verinon\\Pictures\\VietinBankLogo1.jpg");
		ImageIcon ic1 = new ImageIcon(CURRENTDIRECTORY+"\\jars\\VietinBankLogo1.jpg");
		JLabel imageLabel1 = new JLabel(ic1);
		imageLabel1.setBounds(0, 0, 600, 50);
		container.add(imageLabel1);

		//ImageIcon ic2 = new ImageIcon("C:\\Users\\Verinon\\Pictures\\VietinBankLogo2.jpg");
		ImageIcon ic2 = new ImageIcon(CURRENTDIRECTORY+"\\jars\\VietinBankLogo2.jpg");
		JLabel imageLabel2 = new JLabel(ic2);
		imageLabel2.setBounds(600, 40, 200, 200);
		container.add(imageLabel2);
		LOGGER.debug("StartMigration  :: StartMigration :: Exit Constructor");
	}

	public void actionPerformed(ActionEvent ae) {
		
		LOGGER.debug("StartMigration  :: actionPerformed :: Enter Method");
		String str = (String) ae.getActionCommand();

		if (str.equals("Connect")) {
			// Logic
			if (dataBaseNameTextField.getText().isEmpty()) {
				JOptionPane.showMessageDialog(null, "Database Name Mandatory !");
				return;
			}
			if (dataBaseUserIdTextField.getText().isEmpty()) {
				JOptionPane.showMessageDialog(null, "Database User Name Mandatory !");
				return;
			}
			if (dataBasePasswordTextField.getPassword().length == 0) {
				JOptionPane.showMessageDialog(null, "Database User Password Mandatory !");
				return;
			}
			// get database connection details
			try {
				accessConnection = accessDatabase.getAccessConnectionDetails();
				sqlconnection = getSQLConnectionDetails(dataBaseNameTextField.getText(), dataBaseUserIdTextField.getText(), dataBasePasswordTextField.getText());
				session = ExportToDocumentum.createSession(REPOSITORYNAME, USERNAME, PASSWORD);
			} catch (DfException e) {
				// TODO Auto-generated catch block
				JOptionPane.showMessageDialog(null, "MT001- ECM Repository Not Connected !");
				connectionStatusTextField.setBackground(new Color(250, 000, 000));
				connectionStatusTextField.setText("Not Connected");
				LOGGER.error("StartMigration  :: actionPerformed :: SM001"+e);
				e.printStackTrace();
			}
			if (sqlconnection.equals(null) || session.equals(null)) {
				return;
			} else {

				connectionStatusTextField.setBackground(new Color(000, 250, 000));
				connectionStatusTextField.setText("Connected");
			}

		} else if(str.equals("Get Branch Details")) {
			//getting brach code and name from icDoc SQL Database asn set it to dropdown and text field values
			if (connectionStatusTextField.getText().isEmpty() || connectionStatusTextField.getText().equalsIgnoreCase("Not Connected")) {
				JOptionPane.showMessageDialog(null, "Please Connect to Database first !");
				return;
			}
			String branchDetails[] = etd.getBranchDetailsFromICDOCDB(sqlconnection);
			branchCodeDropDown.addItem("Branch "+branchDetails[0]);
			branchNameTextField.setText(branchDetails[1]);
			
		} else if (str.equals("Browse")) {
			if (branchCodeDropDown.getSelectedItem() == null) {
				JOptionPane.showMessageDialog(null, "Please select Branch Code first !");
				return;
			}
			final JFileChooser fc = new JFileChooser();
			fc.setCurrentDirectory(new java.io.File("."));
			fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			fc.setAcceptAllFileFilterUsed(false);
			fc.showOpenDialog(this);
			try {
				File filepath = fc.getSelectedFile();
				
				String yearFolderPath = filepath.getPath();
				if((new File(yearFolderPath+"\\"+"253614bbac999b38b5b60cae531c4969")).exists()) {
					folderPathTextField.setText(filepath.getPath());
				} else if((new File(yearFolderPath+"\\"+"c8758b517083196f05ac29810b924aca")).exists()){
					folderPathTextField.setText(filepath.getPath());
				} else if((new File(yearFolderPath+"\\"+"d7a84628c025d30f7b2c52c958767e76")).exists()){
					folderPathTextField.setText(filepath.getPath());
				} else if((new File(yearFolderPath+"\\"+"f1981e4bd8a0d6d8462016d2fc6276b3")).exists()){
					folderPathTextField.setText(filepath.getPath());
				}else {
					JOptionPane.showMessageDialog(null, "Please Select correct Source Folder !");
				    // File or directory does not exist
				}				

			} catch (Exception e) {
				//JOptionPane.showMessageDialog(null, "MT002-Fails to get browse path !");
				LOGGER.error("StartMigration M002"+e);
				LOGGER.error("StartMigration  :: actionPerformed :: SM002"+e);
				e.printStackTrace();
			}
		} else if (str.equals("Start")) {

			if (connectionStatusTextField.getText().isEmpty() || connectionStatusTextField.getText().equalsIgnoreCase("Not Connected")) {
				JOptionPane.showMessageDialog(null, "Please Connect to Database first !");
				return;
			} else {
				if (folderPathTextField.getText().isEmpty()) {
					JOptionPane.showMessageDialog(null, "Please select the folder !");
					return;
				}
			}
			int selectedValue = JOptionPane.showConfirmDialog(null, "Do you want to start Migration ?");
			if (selectedValue == 0) {
				// incase "OK" selection
				// progressBar.setIndeterminate(true);
				startButton.setEnabled(false);
				try {
					HashMap parentFolderAttributeHashMap = new HashMap();
					parentFolderAttributeHashMap.put("BRANCH_CODE", branchCodeDropDown.getSelectedItem().toString());
					etd.prepareFolderStructure(parentFolderAttributeHashMap, session);
				} catch (DfException e) {
					// TODO Auto-generated catch block
					LOGGER.error("StartMigration  :: actionPerformed :: SM003"+e);
					e.printStackTrace();
					return;
				}
				//Thread thr1 = new Thread(r1);
				extractExportThread = new Thread(extractExportRunnable);
				extractExportThread.start();

			} else if (selectedValue == 1) {
				// incase "NO" selection
				return;
			} else {
				// incase "Stop" selection
				return;
			}

		} else if (str.equals("RerunDocs")) {
			// logic
			//getFailedDocsFromAccessDB();
			if (folderPathTextField.getText().isEmpty()) {
				JOptionPane.showMessageDialog(null, "Please select the folder !");
				return;
			}
			int selectedValue = JOptionPane.showConfirmDialog(null, "Do you want to Rerun Migration tool for failed docs ?");
			if(selectedValue == 0) {
				rerunDocButton.setEnabled(false);
				extractExportFailedDocsThread = new Thread(extractExportFailedDocsRunnable);
				extractExportFailedDocsThread.start();
				//etd.doExportFailedCustDocs(sqlconnection, folderPathTextField.getText(), branchCodeDropDown.getSelectedItem().toString(), accessConnection);
				//rerunButton.setEnabled(true);
			}else {
				// incase "NO" selection
				return;
			}
			

		} else if (str.equals("RerunFolder")) {
			// logic
			//getFailedDocsFromAccessDB();
			if (folderPathTextField.getText().isEmpty()) {
				JOptionPane.showMessageDialog(null, "Please select the folder !");
				return;
			}
			int selectedValue = JOptionPane.showConfirmDialog(null, "Do you want to Rerun Migration tool for failed folders ?");
			if(selectedValue == 0) {
				rerunFolButton.setEnabled(false);
				extractExportFailedFolderThread = new Thread(extractExportFailedFolderRunnable);
				extractExportFailedFolderThread.start();
				//etd.doExportFailedCustDocs(sqlconnection, folderPathTextField.getText(), branchCodeDropDown.getSelectedItem().toString(), accessConnection);
				//rerunButton.setEnabled(true);
			}else {
				// incase "NO" selection
				return;
			}
			

		} else if (str.equals("ViewReport")) {
			// logic
			LOGGER.debug("StartMigration  :: actionPerformed :: View Reprot");
			MigrationReports mr= new MigrationReports();
			mr.setSize(800, 600);
			mr.setTitle("Migration Reports");
			mr.setVisible(true);

		} else if (str.equals("Stop")) {
			//dispose();
			System.exit(0);
		}
		LOGGER.debug("StartMigration  :: actionPerformed :: Exit Method");
	}

	public void blank() {
		dataBaseNameTextField.setText("");
		dataBaseUserIdTextField.setText("");
		dataBasePasswordTextField.setText("");
		connectionStatusTextField.setText("");

	}

	/**
	 * Method Name : getConnectionDetails Description : This method will get and
	 * set the database connection thru DSN
	 * 
	 * @param db
	 *            ,username,password
	 * @exception DfException
	 **/
	public Connection getSQLConnectionDetails(String dbservername, String username, String password) {
		LOGGER.debug("StartMigration  :: getSQLConnectionDetails :: Enter Method");
		Connection Con = null;
		Properties properties = new Properties();
		properties.put("user", username);
		properties.put("password", password);
		properties.put("characterEncoding", "ISO-8859-1");
		properties.put("useUnicode", "true");		  
		//String url = "jdbc:sqlserver://HQ-ECMDTS-DEV.hq.icbv.com:1433;"+"databaseName=Document_HSTD;";
		String url = "jdbc:sqlserver://"+dbservername+":1433;"+"databaseName=Document_HSTD;";
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			Con = DriverManager.getConnection(url, properties);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Database Not Connected !");
			connectionStatusTextField.setBackground(new Color(250, 000, 000));
			connectionStatusTextField.setText("Not Connected");
			LOGGER.error("StartMigration  :: getSQLConnectionDetails :: SM004"+e);
			JOptionPane.showMessageDialog(null, "MT004-Error in connecting the DSN");
			e.printStackTrace();
		}
		LOGGER.debug("StartMigration  :: getSQLConnectionDetails :: Exit Method");
		return Con;
	}

	/**
	 * Method Name : doExtractCustFolders Description : This method will get data
	 * from icdoc and ingest into documentum repository
	 * 
	 * @param connection
	 * @param Branch
	 *            Code
	 * @param Source
	 *            Folder Path
	 * @exception DfException
	 **/
	public String doExtractCustFolders(Connection conn, String branchCode, String sourcDocFolderPath) {
		LOGGER.debug("StartMigration  :: doExtractCustFolders :: Enter Method");

		try {
			statement1 = sqlconnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
			statement2 = sqlconnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
			statement3 = sqlconnection.createStatement();					
			accessStatement = accessConnection.createStatement();
			
			//String getFoldersQuery = "select * from dbo.Document order by Code";
			String getFoldersQuery = RSB.getString("ICDOCFOLDERQUERY");
			noOfIngestedFolders = accessDatabase.getIngestedFoldersCount(ICDOCFOLDERSTABLE, accessStatement);
			
			if (noOfIngestedFolders == 0) {
				LOGGER.debug("StartMigration  :: doExtractCustFolders :: QUERY="+getFoldersQuery);
				folderResultset = statement1.executeQuery(getFoldersQuery);		
				if (folderResultset.last()) {
					MAX = folderResultset.getRow();
					progressBar.setMinimum(0);
					progressBar.setMaximum(MAX);
					folderResultset.beforeFirst(); // not rs.first() because the
				} else {
					LOGGER.debug("StartMigration  :: doExtractCustFolders :: Records Not Exist");
				}

			} else {
				folderResultset = statement2.executeQuery(getFoldersQuery);
				if (folderResultset.last()) {
					MAX = folderResultset.getRow();
					if(noOfIngestedFolders < MAX) {
						progressBar.setMinimum(0);
						progressBar.setMaximum(MAX-noOfIngestedFolders);
						folderResultset.beforeFirst(); // not rs.first() because the
						folderResultset.absolute(noOfIngestedFolders);
					} else {
						JOptionPane.showMessageDialog(null, "Content which you are trying to Migrate already Migrated !!! \n Plese check documents in ECM");
						return "already done";
					}

				} else {
					LOGGER.debug("StartMigration  :: doExtractCustFolders :: Records Not Exist");
				}
			}

			// Starting Progress bar thread, which will in parallel with
			// doExtractAndExport
			//Thread thr2 = new Thread(r2);
			extractExportProgressBarThread = new Thread(extractExportProgressBarRunnable);
			extractExportProgressBarThread.start();

			long startTime, endTime = 0, resultSetCount = 0;
			HashMap custFolderAttributeHashMap = new HashMap(); 
			String isCustFolderCreated = null;
			String codeV, subjectV, numberSignV, creatorNameV, branchV, verifierNameV, dateEnforceV =null ;
			String docAbbreviateNameV,typeDetailV,faCIFV,faIDV,faNameV,participateV,statusNameV =null;
			String originalV,specificDocNameV,tsdbNameV,depNameV,depNameTWV,nameGroupV,codeGroupV=null;
			String statusCodeV,docAbbreviateCodeV,participateCodeV,fieldActionCodeV,tsdbCodeV,SpecificDocCodeV,creditCouncilV=null;
			while (folderResultset.next()) {
				startTime = System.currentTimeMillis();
				branchV = folderResultset.getString("Branch");
				codeV = folderResultset.getString("Code");
				subjectV = folderResultset.getString("Subject");
				numberSignV = folderResultset.getString("Number_Sign");
				creatorNameV = 	folderResultset.getString("Creator");
				verifierNameV = folderResultset.getString("Verifier");
				dateEnforceV = folderResultset.getString("Date_Enforce");
				docAbbreviateNameV = folderResultset.getString("DocAbbreviate");
				typeDetailV = folderResultset.getString("TypeDetail");
				faCIFV = folderResultset.getString("FA_CIF");
				faIDV = folderResultset.getString("FA_ID");
				faNameV = 	folderResultset.getString("FA_Name");
				participateV = folderResultset.getString("Participate");
				statusNameV = folderResultset.getString("Status_Name");
				originalV = folderResultset.getString("Original");
				specificDocNameV = folderResultset.getString("SpecificDoc_Name");
				tsdbNameV = folderResultset.getString("TSDB_Name");
				depNameV = folderResultset.getString("Dep_name");
				depNameTWV = 	folderResultset.getString("Dep_name_TW");
				nameGroupV = folderResultset.getString("name_group");
				codeGroupV = folderResultset.getString("code_group");
				statusCodeV = folderResultset.getString("Status");
				docAbbreviateCodeV = folderResultset.getString("DocAbbreviate_Code");
				participateCodeV = folderResultset.getString("Participate_code");
				fieldActionCodeV = 	folderResultset.getString("FieldAction_Code");
				tsdbCodeV = folderResultset.getString("TSDB");
				SpecificDocCodeV = folderResultset.getString("SpecificDoc");
				creditCouncilV = folderResultset.getString("CreditCouncil");
		
				custFolderAttributeHashMap.put("branch_number",branchV);
				custFolderAttributeHashMap.put("code",codeV);
				custFolderAttributeHashMap.put("folder_subject",subjectV);
				custFolderAttributeHashMap.put("number_sign",numberSignV);
				custFolderAttributeHashMap.put("creator_name",creatorNameV);
				custFolderAttributeHashMap.put("verifier_name",verifierNameV);
				custFolderAttributeHashMap.put("date_enforce",dateEnforceV);
				custFolderAttributeHashMap.put("doc_abbreviate_name",docAbbreviateNameV);
				custFolderAttributeHashMap.put("type_detail",typeDetailV);
				custFolderAttributeHashMap.put("fa_cif",faCIFV);
				custFolderAttributeHashMap.put("fa_id",faIDV);
				custFolderAttributeHashMap.put("fa_name",faNameV);
				custFolderAttributeHashMap.put("participate",participateV);
				custFolderAttributeHashMap.put("status_name",statusNameV);
				custFolderAttributeHashMap.put("original",originalV);
				custFolderAttributeHashMap.put("specific_doc_name",specificDocNameV);
				custFolderAttributeHashMap.put("tsdb_name",tsdbNameV);
				custFolderAttributeHashMap.put("dep_name",depNameV);
				custFolderAttributeHashMap.put("dep_name_tw",depNameTWV);
				custFolderAttributeHashMap.put("name_group",nameGroupV);
				custFolderAttributeHashMap.put("code_group",codeGroupV);
				custFolderAttributeHashMap.put("status_code",statusCodeV);
				custFolderAttributeHashMap.put("doc_abbreviate_code",docAbbreviateCodeV);
				custFolderAttributeHashMap.put("participate_code",participateCodeV);
				custFolderAttributeHashMap.put("field_action_code",fieldActionCodeV);
				custFolderAttributeHashMap.put("tsdb_code",tsdbCodeV);
				custFolderAttributeHashMap.put("specific_doc_code",SpecificDocCodeV);
				custFolderAttributeHashMap.put("credit_council",creditCouncilV);				
				custFolderAttributeHashMap.put("branch_cabinet",branchCodeDropDown.getSelectedItem().toString());
				custFolderAttributeHashMap.put("source_folder_path",folderPathTextField.getText().toString());
				isCustFolderCreated = etd.doCreateCustFolder(custFolderAttributeHashMap, session, statement3, accessStatement, accessConnection, sqlconnection);
				
				//customerfolder created and export documents successfully than insert this folder into access database folder datame with SUCCESS status
				//call update access database table 'icdocfolders'

				accessDatabase.insertExportedFolderIntoAccessDB(codeV, numberSignV, Calendar.getInstance().getTime().toString(), isCustFolderCreated, accessStatement);
				accessConnection.commit();
				current++;
				resultSetCount = resultSetCount + 1;
				endTime = System.currentTimeMillis();
				WAIT = endTime - startTime;
			}
			LOGGER.debug("StartMigration  :: doExtractCustFolders :: Total records in Document Detail Table fetched" + resultSetCount);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, "MT005-Error While reading data from icDoc DB","MT004",2);
			LOGGER.error("StartMigration  :: doExtractCustFolders :: SM005"+e);
			e.printStackTrace();
		} finally {
			LOGGER.debug("StartMigration  :: doExtractCustFolders ::Exit Method");			
		}
		return "done";
	}
	
	/**
	 * @param args
	 */
	/*
	 * public static void main(String[] args) { // TODO Auto-generated method
	 * stub StartMigration s = new StartMigration(); s.setSize(800, 600);
	 * s.setTitle("Migration Tool v1.0"); s.setVisible(true);
	 * 
	 * }
	 */

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LOGGER.debug("StartMigration  :: main :: Enter Method");
		CURRENTDIRECTORY = args[0];
		StartMigration sm = new StartMigration();
		sm.setSize(800, 600);
		sm.setTitle("Migration Tool v1.0");
		sm.setVisible(true);
		LOGGER.debug("StartMigration  :: main :: Exit from Method");

	}

	class SimulatedActivity extends SwingWorker<Void, Integer> {
		/**
		 * Constructs the simulated activity that increments a counter from 0 to
		 * a given target.
		 * 
		 * @param t
		 *            the target value of the counter.
		 */
		public SimulatedActivity(int t) {
			current = 0;
			target = t;
		}

		protected Void doInBackground() throws Exception {
			try {
				while (current < target) {
					Thread.sleep(WAIT);
					// current++;
					publish(current);
				}
			} catch (InterruptedException e) {
				LOGGER.error("StartMigration  :: doInBackground :: SM006"+e);
				e.printStackTrace();
			}
			return null;
		}

		protected void process(List<Integer> chunks) {
			for (Integer chunk : chunks) {
				progressBar.setValue(chunk);
			}
		}

		protected void done() {
			startButton.setEnabled(true);
		}

		private int target;
	}

	Runnable extractExportRunnable = new Runnable() {
		public void run() {
			try {
				String status = doExtractCustFolders(sqlconnection, branchCodeDropDown.getSelectedItem().toString(), folderPathTextField.getText());
			} catch (Exception iex) {
				LOGGER.error("StartMigration  :: extractExportRunnable :: SM007"+iex);
			}
		}
	};

	Runnable extractExportProgressBarRunnable = new Runnable() {
		public void run() {
			try {
				activity = new SimulatedActivity(MAX);
				activity.execute();
			} catch (Exception iex) {				
				LOGGER.error("StartMigration  :: extractExportProgressBarRunnable :: SM008"+iex);
				iex.printStackTrace();
			}
		}
	};
	
	Runnable extractExportFailedDocsRunnable = new Runnable() {
		public void run() {
			try {
				etd.doExportFailedCustDocs(sqlconnection, folderPathTextField.getText(), branchCodeDropDown.getSelectedItem().toString(),progressBar,rerunDocButton,  accessConnection);
			} catch (Exception iex) {
				LOGGER.error("StartMigration  :: extractExportFailedDocsRunnable :: SM008"+iex);
				iex.printStackTrace();
			}
		}
	};
	
	
	Runnable extractExportFailedFolderRunnable = new Runnable() {
		public void run() {
			try {
				statement3 = sqlconnection.createStatement();
				accessStatement = accessConnection.createStatement();
				etd.doExportFailedCustFolders(session, sqlconnection, accessConnection, statement3, accessStatement, folderPathTextField.getText(), branchCodeDropDown.getSelectedItem().toString(),progressBar,rerunFolButton);
				 
			} catch (Exception iex) {
				LOGGER.error("StartMigration  :: extractExportFailedFolderRunnable :: SM008"+iex);
				iex.printStackTrace();
			}
		}
	};

}
